package com.atguigu.eduorder.controller;


import com.atguigu.commonutils.JwtUtils;
import com.atguigu.commonutils.R;
import com.atguigu.eduorder.entity.Order;
import com.atguigu.eduorder.service.OrderService;
import com.atguigu.service.handler.GuliException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 订单 前端控制器
 * </p>
 *
 * @author atguigu
 * @since 2022-09-17
 */
@RestController
@RequestMapping("/eduorder/order")
public class OrderController {
    @Autowired
    private OrderService orderService;

    /**
     *  生成订单信息
     * @param courseId 课程id
     * @param request  请求包含token
     * @return 返回订单id
     */
    @PostMapping("createOrder/{courseId}")
    public R save(@PathVariable String courseId, HttpServletRequest request){
        String memberId = JwtUtils.getMemberIdByJwtToken(request);
        if(StringUtils.isEmpty(memberId)){
            throw new GuliException(20001,"未登录！");
        }
        String orderId=orderService.saveOrder(courseId,memberId);
        return R.ok().data("orderId",orderId);
    }

    /**
     *  根据订单id，获取订单信息
     * @param orderId
     * @return
     */
    @GetMapping("getOrder/{orderId}")
    public R get(@PathVariable String orderId) {
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.eq("order_no",orderId);
        Order order = orderService.getOne(wrapper);
        return R.ok().data("item", order);
    }

    /**
     *  根据用户id和课程id查询订单是否已购买
     * @param memberId 用户id
     * @param id  课程id
     * @return
     */
    @GetMapping("isBuyCourse/{memberId}/{id}")
    public boolean isBuyCourse(@PathVariable("memberId") String memberId,@PathVariable("id") String id){
        //订单1表示支付成功
        QueryWrapper<Order> wrapper=new QueryWrapper<>();
        wrapper.eq("course_id",id);
        wrapper.eq("member_id",memberId);
        wrapper.eq("status",1);
        int count = orderService.count(wrapper);
        if(count>0){
            return true;
        }else{
            return false;
        }
    }

}

